package controller.cartp;

import com.zuche.framework.tradingPlatform.*;
import com.zuche.framework.utils.PropertiesReader;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.Charsets;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by PCG on 2016/5/16.
 */
@Controller
public class OpenApiController {

    private String projectAddress;

    public OpenApiController() {
        this.projectAddress = PropertiesReader.getAppointPropertiesAttribute(
                "setting", "projectAddress", String.class);
    }

    /**
     * 易联wap支付
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("openApiCreateNo.do_")
    @ResponseBody
    public Object createNoSms(HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, "http://10.101.32.9:8083/cartptest/openApiReturn.do_");
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//账户
        paramMap.put(RequestParams.GROUP_TYPE, GroupType.CREATE_NO);
        paramMap.put(RequestParams.BUSINESS_ID, ""+System.currentTimeMillis());
        paramMap.put(RequestParams.BUSINESS_NAME, "openApi");
        paramMap.put(RequestParams.TARGET_GROUP,"openApi");//实际交易类型，openapi
        paramMap.put(RequestParams.SOURCE_ID, CurrenceSource.ALIPAY);//资金来源，支付宝支付
        paramMap.put(RequestParams.COMPLETE_STATUS, Status.WAITING);
        return TradingServiceExecutor.doRpc(paramMap,false);
    }

    @RequestMapping("notifyCreateNo.do_")
    public String notifyCreateNo(HttpServletRequest request,Model model) throws Exception{
        String uniqueId = request.getParameter("uniqueId");
        String status = request.getParameter("status");
        String errMsg = "";
        String businessMoney = request.getParameter("businessMoney");
        String payerId = request.getParameter("payerId");
        String replyId = request.getParameter("replyId");
        String signData = "recordId="+uniqueId;
        signData += "&replyId="+replyId;
        signData += "&businessMoney="+businessMoney;
        signData += "&clientId="+payerId;
        signData += "&status="+status;
        String params = signData + "&errMsg="+errMsg;
        String url = request.getParameter("address")+"/jsp/openAPI/openApiNotify.jsp?"+params+"&sign="+sign(signData);
        model.addAttribute("url",url);
        return "openApiNotify.jsp";
    }

    public static String sign(String data) throws Exception{
        String priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJrYmCarq+70hmF0+8WlmO3g6L5/XoohDDmrPWfzKIaTsZEp0ZsQNHc+o8IQv5Po0G7cQSpM00sfsaHeY5bWOeAhNqcKYBuPKja18bQXynZnnUUbCYd+tMdxv+6Y2yOz9+FxKEiIFe3YJr9XxWakvegfDO7GE2nd+FEgElFIZAVhAgMBAAECgYBz/4PjnEEdrhKpGWCuzIIG2bChXHsvENi+rtg+cfrO7f9cVq6N8hLLraIxdCiAHi1ejyNGE+1JXsHMF/QVAAC0CvgmPSbDZgw98jbKuU8xCfsLzGZzMCLvtkwwS8O3abOs3jgtp2y3XwgDGvoW8Kvy4FVFR3EqrpFJQQVy/FvbQQJBAMn6jSLOTQaae03NyV0RY7dVPHTxn67vdLRfwPmOW/c9ChTRmKV9qiFXllMigCV8NrxSt4IIV+075fgrDB6I3fkCQQDEQuD47vV0Xjdhq63IfpuIrX8QpzWSEtdJv1ETOILRC2vbOvZ9axE8KOd6hvj7ustGCYCnjAQOTT0NzpXTZFypAkAaRfJH/cf9POkfNM6lwZZUCc1kdO3Npq5qrC4BCGikH5eJH76YgGE6Fxeh1tIOjjrcgnIGgylU3b7LamYYLruZAkBpibVE5+siWo/Ze+KF0F9/Dh0oLWKHXI5c3/6PIXJnS4cCayClrO+ltDFWGELHy1kIHpAKiSadMjfEtvSmqm+RAkEAr5Pyyr4Xdn3p6pyMQTidYCE+3UVR8q5DyrhXbjRaJdghGX25jcGeo/qkNqoiJr2IZtEoa0oE8g6hkplm9F8p0w==";
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        byte[] signbyte = signature.sign();
        return Base64.encodeBase64String(signbyte);
    }


    @RequestMapping("/openApiReturn.do_")
    public void openApiReturn(HttpServletRequest request,HttpServletResponse response){

        String status = request.getParameter(ReplyRequestParams.STATUS);
        if(Status.SUCCESS.equals(status)){
            //开始回调处理
            //获得请求时发起的自定义参数
            String selfParam = request.getParameter(RequestParams.CUSTOMIZED_FLAG
                    +"selfParam");
            System.out.println(selfParam);
            try{
                OutputStream output = response.getOutputStream();
                output.write("http://127.0.0.1:8083/cartptest/success.jsp".getBytes());
            }catch (Exception e){
                e.printStackTrace();
            }
            //加入固定标记，通知交易平台回调成功
            response.addHeader("CAR_TP", Boolean.TRUE.toString());
            System.out.println("支付成功回调！");
        }else{
            System.out.println("支付失败回调！");
        }
    }
}
